{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import tkinter\n",
    "from tkinter import simpledialog, colorchooser, filedialog\n",
    "# 需要执行 pip install pillow 安装扩展库\n",
    "from PIL import ImageGrab\n",
    "\n",
    "root = tkinter.Tk()\n",
    "root.title('My Paint----by Dong Fuguo')\n",
    "root['width'] = 800\n",
    "root['height'] = 600\n",
    "\n",
    "# 控制是否允许画图的变量，1：允许，0：不允许\n",
    "canDraw = tkinter.IntVar(value=0)\n",
    "# 控制画图类型的变量，1：曲线，2：直线，3：矩形，4：文本，5：橡皮\n",
    "what = tkinter.IntVar(value=1)\n",
    "# 记录鼠标位置的变量\n",
    "x = tkinter.IntVar(value=0)\n",
    "y = tkinter.IntVar(value=0)\n",
    "# 前景色、背景色\n",
    "foreColor = '#000000'\n",
    "backColor = '#FFFFFF'\n",
    "\n",
    "# 创建画布\n",
    "canvas = tkinter.Canvas(root, bg='white', width=800, height=600)\n",
    "\n",
    "# 鼠标左键单击，允许画图，并记录当前鼠标位置\n",
    "def onLeftButtonDown(event):\n",
    "    canDraw.set(1)\n",
    "    x.set(event.x)\n",
    "    y.set(event.y)\n",
    "    if what.get() == 4:\n",
    "        text = simpledialog.askstring(title=\"Input Text\", prompt=\"Enter the text to draw:\")\n",
    "        if text:\n",
    "            canvas.create_text(event.x, event.y, text=text, fill=foreColor)\n",
    "canvas.bind('<Button-1>', onLeftButtonDown)\n",
    "\n",
    "# 记录最后绘制图形的id\n",
    "lastDraw = 0\n",
    "\n",
    "# 按住鼠标左键移动，画图\n",
    "def onLeftButtonMove(event):\n",
    "    global lastDraw\n",
    "    if canDraw.get() == 0:\n",
    "        return\n",
    "    if what.get() == 1:  # 曲线\n",
    "        canvas.create_line(x.get(), y.get(), event.x, event.y, fill=foreColor)\n",
    "        x.set(event.x)\n",
    "        y.set(event.y)\n",
    "    elif what.get() == 2:  # 直线\n",
    "        try:\n",
    "            canvas.delete(lastDraw)\n",
    "        except Exception as e:\n",
    "            pass\n",
    "        lastDraw = canvas.create_line(x.get(), y.get(), event.x, event.y, fill=foreColor)\n",
    "    elif what.get() == 3:  # 矩形\n",
    "        try:\n",
    "            canvas.delete(lastDraw)\n",
    "        except Exception as e:\n",
    "            pass\n",
    "        lastDraw = canvas.create_rectangle(x.get(), y.get(), event.x, event.y, outline=foreColor)\n",
    "    elif what.get() == 5:  # 橡皮\n",
    "        canvas.create_rectangle(event.x - 5, event.y - 5, event.x + 5, event.y + 5, outline=backColor, fill=backColor)\n",
    "canvas.bind('<B1-Motion>', onLeftButtonMove)\n",
    "\n",
    "# 鼠标左键抬起，不允许再画图了\n",
    "def onLeftButtonUp(event):\n",
    "    global lastDraw\n",
    "    if what.get() == 2:  # 直线\n",
    "        canvas.create_line(x.get(), y.get(), event.x, event.y, fill=foreColor)\n",
    "    elif what.get() == 3:  # 矩形\n",
    "        canvas.create_rectangle(x.get(), y.get(), event.x, event.y, outline=foreColor)\n",
    "    canDraw.set(0)\n",
    "    lastDraw = 0\n",
    "canvas.bind('<ButtonRelease-1>', onLeftButtonUp)\n",
    "\n",
    "# 创建菜单\n",
    "menu = tkinter.Menu(root, tearoff=0)\n",
    "\n",
    "# 打开图像文件\n",
    "def Open():\n",
    "    filename = filedialog.askopenfilename(title='Open Image', filetypes=[('image', '*.jpg *.png *.gif')])\n",
    "    if filename:\n",
    "        image = tkinter.PhotoImage(file=filename)\n",
    "        canvas.create_image(80, 80, image=image)\n",
    "        canvas.image = image  # 保持引用以防止被垃圾回收\n",
    "menu.add_command(label='Open', command=Open)\n",
    "\n",
    "# 保存图像\n",
    "def Save():\n",
    "    left = root.winfo_rootx() + canvas.winfo_x()\n",
    "    top = root.winfo_rooty() + canvas.winfo_y()\n",
    "    right = left + canvas.winfo_width()\n",
    "    bottom = top + canvas.winfo_height()\n",
    "    im = ImageGrab.grab((left, top, right, bottom))\n",
    "    filename = filedialog.asksaveasfilename(title='Save Image', filetypes=[('PNG', '*.png')])\n",
    "    if not filename:\n",
    "        return\n",
    "    if not filename.endswith('.png'):\n",
    "        filename += '.png'\n",
    "    im.save(filename)\n",
    "menu.add_command(label='Save', command=Save)\n",
    "\n",
    "# 清除\n",
    "def Clear():\n",
    "    for item in canvas.find_all():\n",
    "        canvas.delete(item)\n",
    "menu.add_command(label='Clear', command=Clear)\n",
    "menu.add_separator()\n",
    "\n",
    "# 创建子菜单，用来选择绘图类型\n",
    "menuType = tkinter.Menu(menu, tearoff=0)\n",
    "\n",
    "# 选择绘图类型\n",
    "def drawCurve():\n",
    "    what.set(1)\n",
    "menuType.add_command(label='Curve', command=drawCurve)\n",
    "\n",
    "def drawLine():\n",
    "    what.set(2)\n",
    "menuType.add_command(label='Line', command=drawLine)\n",
    "\n",
    "def drawRectangle():\n",
    "    what.set(3)\n",
    "menuType.add_command(label='Rectangle', command=drawRectangle)\n",
    "\n",
    "def drawText():\n",
    "    global text\n",
    "    text = simpledialog.askstring(title=\"Input Text\", prompt=\"Enter the text to draw:\")\n",
    "    what.set(4)\n",
    "menuType.add_command(label='Text', command=drawText)\n",
    "\n",
    "# 选择前景色\n",
    "def chooseForeColor():\n",
    "    global foreColor\n",
    "    foreColor = colorchooser.askcolor()[1]\n",
    "menuType.add_command(label='Choose Foreground Color', command=chooseForeColor)\n",
    "\n",
    "# 选择背景色\n",
    "def chooseBackColor():\n",
    "    global backColor\n",
    "    backColor = colorchooser.askcolor()[1]\n",
    "menuType.add_command(label='Choose Background Color', command=chooseBackColor)\n",
    "\n",
    "# 选择橡皮\n",
    "def onErase():\n",
    "    what.set(5)\n",
    "menuType.add_command(label='Erase', command=onErase)\n",
    "\n",
    "menu.add_cascade(label='Type', menu=menuType)\n",
    "\n",
    "# 鼠标右键抬起，弹出菜单\n",
    "def onRightButtonUp(event):\n",
    "    menu.post(event.x_root, event.y_root)\n",
    "canvas.bind('<ButtonRelease-3>', onRightButtonUp)\n",
    "\n",
    "canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)\n",
    "root.mainloop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pillow in c:\\users\\administrator\\appdata\\local\\programs\\python\\python311\\lib\\site-packages (11.0.0)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "[notice] A new release of pip is available: 24.0 -> 24.3.1\n",
      "[notice] To update, run: python.exe -m pip install --upgrade pip\n"
     ]
    }
   ],
   "source": [
    "pip install pillow"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
